package com.aiYouPms.common.service.impl;

import com.aiYouPms.common.dao.MenuDao;
import com.aiYouPms.common.model.Menu;
import com.aiYouPms.common.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    private final MenuDao menuDao;

    @Autowired
    public MenuServiceImpl(MenuDao menuDao) {
        this.menuDao = menuDao;
    }

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    @Override
    public Menu findById(Long id) {
        return menuDao.findById(id);
    }

    @Override
    public List<Menu> findByParentId(Long parentId) {
        return menuDao.findByParentId(parentId);
    }

    @Override
    @Transactional
    public Menu create(Menu menu) {
        Date now = new Date();
        menu.setCreateTime(now);
        menu.setUpdateTime(now);
        menuDao.insert(menu);
        return menu;
    }

    @Override
    @Transactional
    public Menu update(Long id, Menu menu) {
        Menu existingMenu = menuDao.findById(id);
        if (existingMenu == null) {
            throw new RuntimeException("菜单不存在");
        }
        
        menu.setId(id);
        menu.setUpdateTime(new Date());
        menuDao.update(menu);
        return menu;
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        Menu existingMenu = menuDao.findById(id);
        if (existingMenu == null) {
            throw new RuntimeException("菜单不存在");
        }

        // 先删除子菜单
        menuDao.deleteByParentId(id);
        // 再删除当前菜单
        menuDao.deleteById(id);
    }
}